package com.qyer.commons.concurrent.assemblingline;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.qyer.commons.concurrent.ArrayListBulk;
import com.qyer.commons.utils.JsonOperator;
import org.apache.commons.collections4.CollectionUtils;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.List;

/**
 * User: Z J Wu Date: 2016/06/06 Time: 17:19 Package: com.qyer.commons.concurrent
 */
public class ResultWriter<I, O> extends AbstractHandler<ArrayListBulk<I>, ArrayListBulk<O>>
  implements Closeable {

  private PrintWriter pw;

  public ResultWriter(StatisticContext context, String output) throws FileNotFoundException {
    super(context);
    this.pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(output))));
  }

  @Override
  public void close() throws IOException {
    if (this.pw != null) {
      this.pw.close();
    }
  }

  @Override
  public ArrayListBulk<O> handle(ArrayListBulk<I> bulk) throws HandleException {
    if (bulk == null) {
      return null;
    }
    List<I> list = bulk.getList();
    if (CollectionUtils.isEmpty(list)) {
      return null;
    }
    try {
      for (I i : list) {
        pw.write(JsonOperator.getInstance().toJson(i));
        pw.write('\n');
      }
    } catch (JsonProcessingException e) {
      throw new HandleException(e);
    }
    return null;
  }
}
